package com.xx.secret.notify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xx.secret.core.OpenContextProvider;
import com.xx.secret.core.IOpenVerify;
import com.xx.secret.entity.CallbackLog;
import com.xx.secret.enums.OpenEnum;
import com.xx.secret.util.AppUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：wangcheng
 * @date 2024/3/13
 **/
@RestController
@RequestMapping("/three/notify")
@Slf4j
public class OpenAbstractNotifyController {

    @Autowired(required = false)
    private INotifyRecordHandler INotifyRecordHandler;

    @RequestMapping("/{apiName}/**")
    public Object handlerNotify(HttpServletRequest request,@PathVariable String apiName) {
        String urlSuffix = StringUtils.substringAfter(request.getServletPath(), apiName+"/");
        log.info("三方api回调 apiName: {} urlSuffix: {} ",apiName,urlSuffix);
        CallbackLog callbackLog = new CallbackLog();
        callbackLog.setApiName(apiName);
        Object resp;
        try {
            int code = OpenEnum.getCodeByApiName(apiName);

            callbackLog.setPlatForm(code);

            JSONObject param = AppUtil.getParam();

            log.info("三方api回调参数: {} ,apiName: {} ,业务参数: {} ", JSON.toJSONString(param),apiName,urlSuffix);

            callbackLog.setMethodSuffix(urlSuffix);

            String notifyUrl = apiName.concat("/").concat(urlSuffix);

            INotifyProcessor notifyClazz = OpenContextProvider.getNotifyClazz(notifyUrl);

            IOpenVerify loanVerifyClazz = null;
            if (notifyClazz.needVerify()) {

                loanVerifyClazz = OpenContextProvider.getLoanVerifyClazz(apiName);
                //验签
                loanVerifyClazz.verify(param);

                param = JSON.parseObject(loanVerifyClazz.decryptParam(param));
            }
            //记录回调日志
            callbackLog.setContentJson(JSON.toJSONString(param));

            //执行回调业务
            NotifyResult result = notifyClazz.handlerNotify(urlSuffix, param);

            callbackLog.setThirdId(result.getThirdId());

            callbackLog.setThirdStatus(result.getThirdStatus());
            if (loanVerifyClazz!=null) {
                //可加密返回
                resp =  loanVerifyClazz.encryptResponse(result.getResult());
            }else {
                resp = result.getResult();
            }
        } catch (Exception e) {
            log.error("三方贷款对接回调处理失败 e: {} apiName: {} ,urlSuffix: {} ", e.getMessage(), apiName, urlSuffix, e);
            callbackLog.setCallStatus(false);
            String message = e.getMessage();
            callbackLog.setFailureReason(StringUtils.substring(message,0,255));
            JSONObject error = new JSONObject();
            error.put("msg", e.getMessage());
            error.put("code", 300);
            resp = error;
        }
        // 项目实现NotifyRecordHandler 可对回调内容进行记录或转发
        log.info("记录回调日志信息");
        if (INotifyRecordHandler !=null) {
            try {
                INotifyRecordHandler.record(callbackLog);
            }catch (Exception e) {
            }
        }
        return resp;

    }
}
